<template>
  <div class="content">
    <div class="contentForm">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        class="form"
      >
        <el-form-item
          label="模版名称:"
          prop="name"
        >
          <div style="display: flex; align-items: center; justify-content: space-between">
            <el-input
              v-model="ruleForm.name"
              clearable
              placeholder="请输入模版名称"
              style="width: 270px"
            ></el-input>
            <!-- <el-button
              type="text"
              size="medium"
              @click="showPreview = true"
            >模版效果预览</el-button> -->
          </div>
        </el-form-item>
        <el-form-item
          v-if="row.activeName == 'recharge'"
          label="分销方:"
          prop="distributor_id"
        >
          <div style="display: flex; align-items: center; justify-content: space-between">
            <el-select
              v-model="ruleForm.distributor_id"
              clearable
              style="width: 270px"
              placeholder="请选择分销方"
            >
              <el-option
                v-for="(item, index) in distributorList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <!-- <el-form-item
          v-if="row.activeName=='recharge'"
          label="默认模版:"
          prop="is_use"
        >
          <el-checkbox
            v-model="ruleForm.is_use"
            :label="1"
          >设置为默认模版</el-checkbox>
        </el-form-item> -->
        <div
          v-for="(tem, temIndex) in templateGrade"
          :key="temIndex"
          class="templateGrade"
        >
          <div class="setLabel rowFlex spaceBetween columnCenter">
            <div style="display: flex; align-items: center; justify-content: space-between; width: 100%">
              <span>{{ tem.type === 'first' ? '首充档位' : '复充档位' }}</span>
              <span>
                <span
                  v-if="tem.type !== 'first'"
                  @click="onCopyFirst"
                >
                  <SvgIcon
                    icon-class="copy_tow"
                    class="iconFont"
                  ></SvgIcon>

                  复制首充档位
                </span>
                <i
                  class="el-icon-circle-plus iconFont"
                  @click="addGrade(tem)"
                ></i>
                添加
              </span>
            </div>

            <!-- <el-button
              v-if="tem.type === 'first'"
              type="text"
              size="medium"
              @click="showPreview = true"
            >模版效果预览</el-button> -->
          </div>
          <div
            v-if="tem.type == 'first'"
            class="first_msg"
            style="color: #999; font-size: 14px; margin: 5px 0"
          >说明：角标支持自定义，非必填，最多12个字，不填则不显示</div>

          <div v-if="ruleForm[tem.list].length > 0">
            <div class="firstRecharge">
              <vuedraggable v-model="ruleForm[tem.list]">
                <transition-group>
                  <div
                    v-for="(item, index) in ruleForm[tem.list]"
                    :key="index"
                    class="rechargeItem"
                  >
                    <div class="rowFlex columnCenter">
                      <span>档位{{ index + 1 }}</span>
                      <el-select
                        v-model="item.product_type"
                        :clearable="false"
                        placeholder="请选择"
                        style="width: 100px"
                        @change="onProductTypeChange(tem.list, index)"
                      >
                        <!-- v-for="item in selectOption" -->
                        <el-option
                          v-for="it in selectOption"
                          :key="it.value"
                          :label="it.label"
                          :value="it.value"
                        > </el-option>
                      </el-select>
                      <div v-if="item.product_type == 1">
                        <span>充</span>
                        <el-input
                          v-model="item.amount"
                          clearable
                          type="number"
                          :step="0.01"
                          style="width: 100px"
                          placeholder="请输入金额"
                          @input="blurCoin(item, index, tem)"
                        ></el-input>
                        <span>元，赠</span>
                        <el-input
                          v-model="item.free_coin"
                          clearable
                          oninput="value=value.replace(/[^0-9]/g, '')"
                          style="width: 100px"
                          placeholder="请输入金额"
                        ></el-input>
                        <!-- @change="freeCoinChange(item,index,tem.list)" -->
                        <span>赠币，</span>
                      </div>
                      <div
                        v-else-if="item.product_type != 11"
                        class="vip_amount"
                      >
                        <!--   oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"-->
                        <el-input
                          v-model="item.amount"
                          type="number"
                          clearable
                          :step="0.01"
                          :style="'width: 200px; margin-left: 20px ;'"
                          placeholder="请输入金额"
                          @input="blurCoinVip(item, index, tem)"
                        ></el-input>
                        <span>元</span>
                        <!-- <p
                          v-if="item.product_type == 2 && item.amount < 69 && item.amount"
                          class="vip_year_tipe"
                        >包年会员最低设置69</p> -->
                      </div>
                      <div
                        v-else
                        class="vip_amount"
                      >
                        <span>充</span>
                        <el-input
                          v-model="item.amount"
                          clearable
                          type="number"
                          style="width: 100px"
                          :step="0.01"
                          placeholder="请输入金额"
                          @input="blurCoin(item, index, tem)"
                        ></el-input>
                        <span>元，解锁</span>
                        <el-input
                          v-model="item.chapter_count"
                          clearable
                          oninput="value=value.replace(/[^0-9]/g, '')"
                          style="width: 100px"
                          placeholder="请输入集数"
                        ></el-input>
                        <span>集</span>
                      </div>
                      <div class="vip_amount">
                        <span>角标</span>
                        <!--   oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"-->
                        <el-input
                          v-model="item.subscript"
                          :style="'width: 100px;'"
                          type="text"
                          clearable
                          maxlength="12"
                          placeholder="请输入文字"
                        ></el-input>
                        <!-- <p
                          v-if="item.product_type == 2 && item.amount < 69 && item.amount"
                          class="vip_year_tipe"
                        >包年会员最低设置69</p> -->
                      </div>
                      <i
                        class="el-icon-remove-outline iconFont"
                        @click="removeGrade(item, index, tem)"
                      ></i>
                    </div>

                    <div style="display: flex; align-content: center">
                      <div class="rowFlex columnCenter recommend">
                        <div class="label">推荐设置</div>
                        ：<el-switch
                          v-model="item.is_recommend"
                          :active-value="'1'"
                          :inactive-value="'0'"
                          @change="onRecommendChange(tem.list, index)"
                        > </el-switch>
                      </div>
                      <div
                        class="infoIcon"
                        style="display: flex; align-items: center"
                      >
                        <div
                          v-show="item.product_type == 1"
                          class="subText"
                        >即:{{ parseFloat((item.amount * 100).toFixed(2)) || 0 }}喵币+{{ item.free_coin || 0 }}赠币</div>
                      </div>
                      <!-- <p
                        v-if="item.product_type == 2 && item.amount < 69 && item.amount"
                        class="vip_year_tipe"
                      >包年会员最低设置69</p> -->
                    </div>
                  </div>
                </transition-group>
              </vuedraggable>
            </div>
          </div>
          <!--充值挽留  -->
          <div
            v-if="tem.type == 'first'"
            class="chargeRetain"
          >
            <div class="title">充值挽留 <el-switch
              v-model="ruleForm.discount_config.status"
              :inactive-value="2"
              :active-value="1"
            ></el-switch></div>
            <div
              v-if="ruleForm.discount_config.status == 1"
              class="chargeRetainContent"
            >
              <div class="title">用户属性满足</div>
              <div class="attribute rowFlex">
                <div class="huoLeft">
                  <div
                    class="and_or"
                    @click="ruleForm.discount_config.condition.type == 1 ? (ruleForm.discount_config.condition.type = 2) : (ruleForm.discount_config.condition.type = 1)"
                  >{{ ruleForm.discount_config.condition.type == 1 ? '且' : '或' }}</div>
                </div>
                <div class="huoRight">
                  <p class="rowFlex columnCenter huoRightItem">
                    <el-checkbox
                      v-model="close_template_num"
                      style="margin-right: 10px"
                    ></el-checkbox>
                    用户在播放页关闭充值模板次数超过<el-input-number
                      v-model="ruleForm.discount_config.condition.close_template_num"
                      style="margin: 0 10px; width: 90px"
                      controls-position="right"
                      :min="0"
                      :max="10000"
                      :step="1"
                      @input.native="numChange($event)"
                    ></el-input-number> 次
                  </p>
                  <p class="rowFlex columnCenter huoRightItem">
                    <el-checkbox
                      v-model="cancel_pay_num"
                      style="margin-right: 10px"
                    ></el-checkbox>
                    用户在播放页取消充值超过<el-input-number
                      v-model="ruleForm.discount_config.condition.cancel_pay_num"
                      style="margin: 0 10px; width: 90px"
                      controls-position="right"
                      :step="1"
                      :min="0"
                      :max="10000"
                      @input.native="numChange($event)"
                    ></el-input-number> 次
                  </p>
                </div>
              </div>
              <div class="retainContent">
                <div class="title">挽留类型</div>
                <el-radio-group
                  v-model="ruleForm.discount_config.discount_type"
                  @change="onDiscountType"
                >
                  <el-radio :label="1">指定档位挽留</el-radio>
                  <el-radio :label="2">档位打折挽留</el-radio>
                </el-radio-group>
                <div
                  v-if="ruleForm.discount_config.discount_type == 1"
                  class="rechargeContent columnFlex rowCenter"
                >
                  <div
                    class="gearRetain rowFlex rechargeItem"
                    style="padding-bottom:20px;"
                  >
                    <span style="margin-right: 10px; margin-top: 5px">挽留档位</span>
                    <el-select
                      v-model="ruleForm.discount_config.discount_info.product_type"
                      :clearable="false"
                      placeholder="请选择"
                      style="width: 100px"
                      @change="ruleForm.discount_config.discount_info.amount = 0"
                    >
                      <el-option
                        v-for="it in selectOption"
                        :key="it.value"
                        :label="it.label"
                        :value="it.value"
                      > </el-option>
                    </el-select>
                    <div v-if="ruleForm.discount_config.discount_info.product_type == 1">
                      <div>
                        <span style="margin: 0 10px">充</span>
                        <el-input
                          v-model="ruleForm.discount_config.discount_info.amount"
                          :clearable="false"
                          :step="0.01"
                          type="number"
                          style="width: 100px"
                          placeholder="请输入金额"
                          @input="moneyInput"
                        ></el-input>
                        <span style="margin: 0 10px">元，赠</span>
                        <el-input
                          v-model="ruleForm.discount_config.discount_info.free_coin"
                          clearable
                          :step="0.01"
                          oninput="value=value.replace(/[^0-9]/g, '')"
                          style="width: 100px"
                          placeholder="请输入金额"
                        ></el-input>
                        <span style="margin: 0 10px">赠币</span>
                      </div>
                    </div>
                    <div
                      v-else-if="ruleForm.discount_config.discount_info.product_type != 11"
                      class="vip_amount"
                    >
                      <!--   oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"-->
                      <el-input
                        v-model="ruleForm.discount_config.discount_info.amount"
                        clearable
                        oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                        :style="'width: 200px; margin-left: 20px ;'"
                        placeholder="请输入金额"
                      ></el-input>
                      <span style="margin: 0 10px">元</span>
                      <!-- <p
                          v-if="item.product_type == 2 && item.amount < 69 && item.amount"
                          class="vip_year_tipe"
                        >包年会员最低设置69</p> -->
                    </div>
                    <div
                      v-else
                      class="vip_amount"
                    >
                      <span>充</span>
                      <el-input
                        v-model="ruleForm.discount_config.discount_info.amount"
                        clearable
                        type="number"
                        style="width: 100px"
                        placeholder="请输入金额"
                        :step="0.01"
                        @input="blurCoin(item, index, tem)"
                      ></el-input>
                      <span>元，解锁</span>
                      <el-input
                        v-model="ruleForm.discount_config.discount_info.chapter_count"
                        clearable
                        oninput="value=value.replace(/[^0-9]/g, '')"
                        style="width: 100px"
                        placeholder="请输入集数"
                      ></el-input>
                      <span>集</span>
                    </div>
                  </div>
                  <div
                    v-if="ruleForm.discount_config.discount_info.product_type==1"
                    class="infoIcon"
                    style="display: flex; align-items: center; margin-left: 0;margin-top:-20px;"
                  >
                    <div class="subText">即:{{ parseFloat((ruleForm.discount_config.discount_info.amount * 100).toFixed(2)) || 0 }}喵币+{{ ruleForm.discount_config.discount_info.free_coin || 0 }}赠币</div>
                  </div>
                </div>
                <div
                  v-else-if="ruleForm.discount_config.discount_type == 2"
                  class="gearRetain rowFlex columnCenter"
                >
                  挽留折扣 <span style="margin-left: 20px">满</span><el-input-number
                    v-model="ruleForm.discount_config.discount_info.amount"
                    style="margin: 0 10px; width: 120px"
                    controls-position="right"
                    :min="1"
                    :max="10000"
                  ></el-input-number>元，打
                  <el-form-item
                    prop="discountNum"
                    label-width="0"
                  >
                    <el-input
                      v-model="ruleForm.discountNum"
                      clearable
                      style="width: 120px; margin-left: 10px; margin-right: 10px"
                      placeholder="请输入1-9.9"
                      oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,1})?).*$/g, '$1')"
                    > </el-input> </el-form-item>折
                  <div
                    class="redText"
                    style="font-size: 12px; margin-left: 20px"
                  >仅限喵币充值档位，其他档位不参与</div>
                </div>
                <!--  -->
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="setLabel rowFlex spaceBetween columnCenter">
        <div><span>复充档位设置</span> <i class="el-icon-circle-plus-outline iconFont"></i> </div>
      </div> -->
      </el-form>
    </div>
    <span class="dialog-footer rowFlex">
      <el-button
        class="btn"
        @click="close"
      >取 消</el-button>
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click="submit"
      >确 定</el-button>
    </span>
    <div
      v-if="showPreview"
      class="left"
    >
      <div class="top">
        <div>模板预览</div>
        <i
          class="el-icon-close"
          @click="showPreview = false"
        ></i>
      </div>
      <div class="content">
        <MobilePreview :row="ruleForm"> </MobilePreview>
      </div>
    </div>
  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon/index.vue'
import MobilePreview from './MobilePreview.vue'
import { mapState, mapActions } from 'vuex'
import { rechargeAdd, prodctTypeList } from '@/api/recharge'
import vuedraggable from 'vuedraggable'
import preview from './preview.vue'
import { paymentList } from '@/api/payment'
import { commonData } from '@/api/common'
import { validateDiscount, checkMoney, reqeustPayInfo } from '@/utils/index'
export default {
  components: {
    preview,
    SvgIcon,
    vuedraggable,
    MobilePreview
  },
  props: {
    row: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      close_template_num: false,
      cancel_pay_num: false,
      radioValue: '',
      ruleForm: {
        discountNum: '',
        mini_app_id: '',
        name: '',
        is_use: '',
        distributor_id: '',
        discount_config: {
          status: 2, // 1开启 2 关闭
          condition: {
            type: 1, // 1且 2 或
            close_template_num: '',
            cancel_pay_num: ''
          },
          discount_type: 1, // 1 指定档位 2 档位打折
          discount_info: { product_type: '1', amount: 0, coin: 0, free_coin: 0, subscript: '', discount: '' }
        },
        first_list: [
          // product_type 1充币 2充会员
          { product_type: '1', amount: 0, coin: 0, free_coin: 0, subscript: '' }
        ],
        repeat_list: [{ product_type: '1', amount: 0, coin: 0, free_coin: 0, subscript: '' }]
      },
      distributorList: [],
      paymentRestrict: {},
      loading: false,
      retainValue: 1,
      showPreview: false,
      templateGrade: [
        { type: 'first', list: 'first_list' },
        { type: 'repeat', list: 'repeat_list' }
      ],
      free_coin_scale: 0,
      chapter_count: 0,
      isLimit: false,
      selectOption: [],
      rules: {
        name: [{ required: true, message: '请输入模版名字', trigger: 'blur' }],
        distributor_id: [{ required: true, message: '请选择分销方', trigger: 'blur' }],
        api_secret: [{ required: true, message: '请输入商户支付秘钥', trigger: 'blur' }],
        private_key: [{ required: true, message: '请输入商户支付私钥', trigger: 'blur' }],
        serial: [{ required: true, message: '请输入证书序列号', trigger: 'blur' }],
        discountNum: [{ required: true, validator: validateDiscount, trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapState('common', ['commonDataList'])
  },
  async mounted() {
    if (this.row.activeName === 'recharge') {
      this.ruleForm.distributor_id = ''
    }
    reqeustPayInfo()
    this.requestDistributor()
    await this.paymentInfo()
    this.init()
    this.GetProdctTypeList()
    this.showPreview = true
  },
  updated() {
    this.$nextTick()
  },
  methods: {
    onDiscountType() {
      // this.ruleForm.discount_config.discount_type
    },
    ...mapActions('common', ['requestCommonData']),
    onCopyFirst() {
      const copyArr = JSON.parse(JSON.stringify(this.ruleForm.first_list))
      this.$set(
        this.ruleForm,
        'repeat_list',
        copyArr.map((item) => {
          const copyObj = item
          delete copyObj.product_id
          return copyObj
        })
      )
    },
    numChange(e) {
      e.target.value = e.target.value.replace(/[^\d]/g, '')
    },
    changeMessage() {
      this.$forceUpdate()
    },
    // discountBlur(evnet) {
    //   if (!/^([1-9]{1})(.\d{1})?$/.test(this.ruleForm.discount)) {
    //     this.$message.warning('折扣数在 1-9.9之间')
    //     this.ruleForm.discount_config.discount_info.discount = 1
    //   }
    // },
    requestDistributor() {
      commonData({ type: 'miniAppDistributor', mini_app_id: window.localStorage.getItem('mini_app_id') }).then((res) => {
        if (res.data.data.length > 0) {
          this.distributorList = res.data.data
          if (this.row.id) {
            this.ruleForm.distributor_id = this.row.distributor_id
          } else {
            const List = this.distributorList.find((item) => item.is_default == 1)
            console.log(List)
            this.ruleForm.distributor_id = (List && List.value) || ''
          }
        }
      })
    },
    freeCoinChange(item, index, list) {
      if (this.free_coin_scale && this.free_coin_scale !== '') {
        if (item.free_coin > item.amount * this.free_coin_scale) {
          this.$message.warning(`当前档位赠币最多${Math.floor(item.amount * this.free_coin_scale)}`)
          this.ruleForm[list][index].free_coin = 0
          this.isLimit = true
        } else {
          this.isLimit = false
        }
      } else {
        this.isLimit = false
      }
    },
    paymentInfo() {
      return new Promise((resolve, reject) => {
        paymentList().then((res) => {
          if (res.data.data && res.data.data.limit_config) {
            this.paymentRestrict = res.data.data.limit_config
            this.free_coin_scale = this.paymentRestrict.coin_height
            this.chapter_count = this.paymentRestrict.chapter_count
          }
          resolve(res)
        })
      })
    },
    onProductTypeChange(key, index) {
      this.selectOption.forEach((item, i) => {
        if (this.ruleForm[key][index].product_type === item.value) {
          this.ruleForm[key][index].product_name = item.label
          this.ruleForm[key][index].amount = 0
          this.ruleForm[key][index].coin = 0
          this.ruleForm[key][index].free_coin = 0
        }
      })
    },
    onRecommendChange(key, index) {
      this.ruleForm[key].forEach((item, i) => {
        if (i !== index) {
          this.ruleForm[key][i].is_recommend = 0
        }
      })
    },
    init() {
      this.requestCommonData({ type: 'merchant' })
      // 编辑的时候
      if (this.row.id) {
        const row = JSON.parse(JSON.stringify(this.row))
        this.ruleForm.name = row.name
        this.ruleForm.is_use = row.is_use == '1'
        this.ruleForm.first_list = row.first_list.map((item) => {
          const obj = item
          if (this.row.copy) {
            delete obj.product_id
          }
          obj.amount = obj.amount.replace(/[^\d\.-]/g, '')
          return obj
        })
        this.ruleForm.repeat_list = row.repeat_list.map((item) => {
          const obj = item
          if (this.row.copy) {
            delete obj.product_id
          }
          obj.amount = obj.amount.replace(/[^\d\.-]/g, '')
          return obj
        })
        if (row.discount_config && row.discount_config.status == 1) {
          this.ruleForm.discount_config = row.discount_config
          this.ruleForm.discount_config.status = Number(row.discount_config.status)
          this.ruleForm.discount_config.condition.close_template_num = Number(row.discount_config.condition.close_template_num)

          this.ruleForm.discount_config.condition.cancel_pay_num = Number(row.discount_config.condition.cancel_pay_num)
          if (this.ruleForm.discount_config.condition.close_template_num > 0) {
            this.close_template_num = true
          } else {
            this.close_template_num = false
          }
          if (this.ruleForm.discount_config.condition.cancel_pay_num > 0) {
            this.cancel_pay_num = true
          } else {
            this.cancel_pay_num = false
          }
          if (!this.ruleForm.discount_config?.discount_info?.discount) {
            this.ruleForm.discountNum = 0
          } else {
            this.ruleForm.discountNum = Number(this.ruleForm.discount_config.discount_info.discount)
          }
        } else {
          this.ruleForm.discount_config = {
            status: 2, // 1开启 2 关闭
            condition: {
              type: '1', // 1且 2 或
              close_template_num: '',
              cancel_pay_num: ''
            },
            discount_type: 1, // 1 指定档位 2 档位打折
            discount_info: { product_type: '1', amount: 0, coin: 0, free_coin: 0, subscript: '', discount: '' }
          }
        }
        if (!this.row.copy) {
          this.ruleForm.id = row.id
        }
      }
    },
    async GetProdctTypeList() {
      const res = await prodctTypeList()
      if (res.status_code == 1) {
        this.selectOption = res.data.map((item) => {
          this.handleFreeLimit(item)
          return {
            ...item,
            value: item.value + ''
          }
        })
      }
    },
    handleFreeLimit(item) {
      switch (item.value) {
        case 1: // 充值喵币送赠币的比例
          item.free_coin_limit = 'coin_height'
          break
        case 2: // 会员包年
          item.free_coin_limit = 'vip_year'
          break
        case 3: // 会员包3天
          item.free_coin_limit = 'vip_three_day'
          break
        case 4: // 包7天
          item.free_coin_limit = 'vip_week'
          break
        case 5: // 包15天
          item.free_coin_limit = 'vip_half_month'
          break
        case 6: // 包月
          item.free_coin_limit = 'vip_month'
          break
        case 7: // 包季
          item.free_coin_limit = 'vip_season'
          break
        case 8: // 半年
          item.free_coin_limit = 'vip_half_year'
          break
        case 9: // 解锁全集
          item.free_coin_limit = 'single_playlet'
          break
        case 10: // 包1天
          item.free_coin_limit = 'vip_day'
          break
        case 11: // 消费集
          item.free_coin_limit = 'single_chapter'
          item.max_free_coin_limit_value = this.paymentRestrict.single_chapter_max
          break
        default:
          break
      }
      item.free_coin_limit_value = this.paymentRestrict[item.free_coin_limit]
    },
    // 新增档位
    addGrade(tem) {
      this.ruleForm[tem.list].push({ product_type: '1', amount: '', coin: '', free_coin: '', subscript: '' })
    },
    blurCoinVip(item, index, tem) {
      if (item.amount !== '') {
        this.$set(this.ruleForm[tem.list][index], 'amount', item.amount.match(/\d+\.?\d{0,2}/, '')[0])
      }
    },
    blurCoin(item, index, tem) {
      this.$set(this.ruleForm[tem.list][index], 'coin', parseFloat((item.amount * 100).toFixed(2)))
      if (item.amount !== '') {
        this.$set(this.ruleForm[tem.list][index], 'amount', item.amount.match(/\d+\.?\d{0,2}/, '')[0])
      }
    },
    moneyInput() {
      this.ruleForm.discount_config.discount_info.amount = checkMoney(this.ruleForm.discount_config.discount_info.amount)
    },
    removeGrade(item, index, tem) {
      if (this.ruleForm[tem.list].length === 1) {
        this.$message.warning('至少保留一个档位')
        return
      }
      this.ruleForm[tem.list].splice(index, 1)
    },
    handleAmountLimitDiscount() {
      if (!Number(this.ruleForm.discount_config.discount_info.amount) || Number(this.ruleForm.discount_config.discount_info.amount) == 0) {
        this.isLimit = true
        this.$message.warning('请输入金额')
        return
      }
      if (!this.cancel_pay_num && !this.close_template_num) {
        this.isLimit = true
        this.$message.warning('请至少选择一项用户属性')
        return
      }
      if (this.cancel_pay_num && (Number(this.ruleForm.discount_config.condition.cancel_pay_num) <= 0 || !this.ruleForm.discount_config.condition.cancel_pay_num)) {
        this.$message.warning('次数必须大于0')
        this.isLimit = true
        return
      }
      if (this.close_template_num && (Number(this.ruleForm.discount_config.condition.close_template_num) == 0 || !this.ruleForm.discount_config.condition.close_template_num)) {
        this.$message.warning('次数必须大于0')
        this.isLimit = true
        return
      }

      if (!this.cancel_pay_num) {
        this.ruleForm.discount_config.condition.cancel_pay_num = 0
      }
      if (!this.close_template_num) {
        this.ruleForm.discount_config.condition.close_template_num = 0
      }
      // if (this.ruleForm.discount_config.discount_info.discount == '') {
      //   this.$message.warning('请输入折扣')
      //   return
      // }
      const isLimit = this.selectOption.find((items) => items.value === this.ruleForm.discount_config.discount_info.product_type)
      // 会员的充值限制
      this.$message.close()
      if (this.ruleForm.discount_config.discount_type == 2) {
        return
      }
      if (isLimit.free_coin_limit === 'single_chapter') {
        console.log(isLimit, '--------------')
        const num = this.ruleForm.discount_config.discount_info.amount / this.ruleForm.discount_config.discount_info.chapter_count
        if (!this.ruleForm.discount_config.discount_info.chapter_count || this.ruleForm.discount_config.discount_info.chapter_count <= 0) {
          this.$message.warning(`解锁单集解锁集数最少为1`)
          this.isLimit = true
          return
        }
        if (num.toFixed(4) < isLimit.free_coin_limit_value) {
          this.$message.warning(`解锁单集每集最低${isLimit.free_coin_limit_value}元-最高${isLimit.max_free_coin_limit_value}元`)
          this.isLimit = true
          return
        }
        if (num.toFixed(4) > Number(isLimit.max_free_coin_limit_value).toFixed(4)) {
          this.$message.warning(`解锁单集每集最低${isLimit.free_coin_limit_value}元-最高${isLimit.max_free_coin_limit_value}元`)
          this.isLimit = true
          return
        }
      } else if (isLimit && Number(this.ruleForm.discount_config.discount_info.amount) < Number(isLimit.free_coin_limit_value) && isLimit.free_coin_limit !== 'coin_height') {
        this.$message.warning(`${isLimit.label}最低${isLimit.free_coin_limit_value}元`)
        this.isLimit = true
        return
      } else if (isLimit.free_coin_limit === 'coin_height') {
        if (this.free_coin_scale && this.free_coin_scale !== '') {
          if (this.ruleForm.discount_config.discount_info.free_coin > this.ruleForm.discount_config.discount_info.amount * this.free_coin_scale) {
            this.$message.warning(`当前档位赠币最多${Math.floor(this.ruleForm.discount_config.discount_info.amount * this.free_coin_scale)}`)
            this.isLimit = true
            return
          }
        } else {
        }
      } else {
      }
    },
    handleAmountLimit(list) {
      list.forEach((item) => {
        // 找出类型相同项
        const isLimit = this.selectOption.find((items) => items.value === item.product_type)
        console.log(isLimit, 'isLimit', item, this.selectOption)
        // 会员的充值限制
        this.$message.close()
        if (isLimit.free_coin_limit === 'single_chapter') {
          const num = item.amount / item.chapter_count
          console.log(item.chapter_count, '-------------')
          if (!item.chapter_count || item.chapter_count <= 0) {
            this.$message.warning(`解锁单集解锁集数最少为1`)
            this.isLimit = true
            return
          }
          console.log(num.toFixed(4), isLimit.free_coin_limit_value, '-----------------')
          if (num.toFixed(4) < isLimit.free_coin_limit_value) {
            this.$message.warning(`解锁单集每集最低${isLimit.free_coin_limit_value}元-最高${isLimit.max_free_coin_limit_value}元`)
            this.isLimit = true
            return
          }
          if (num.toFixed(4) > Number(isLimit.max_free_coin_limit_value).toFixed(4)) {
            this.$message.warning(`解锁单集每集最低${isLimit.free_coin_limit_value}元-最高${isLimit.max_free_coin_limit_value}元`)
            this.isLimit = true
            return
          }
        } else if (isLimit && Number(item.amount) < Number(isLimit.free_coin_limit_value) && isLimit.free_coin_limit !== 'coin_height') {
          this.$message.warning(`${isLimit.label}最低${isLimit.free_coin_limit_value}元`)
          this.isLimit = true
          return
        } else if (isLimit.free_coin_limit === 'coin_height') {
          if (this.free_coin_scale && this.free_coin_scale !== '') {
            if (item.free_coin > item.amount * this.free_coin_scale) {
              this.$message.warning(`当前档位赠币最多${Math.floor(item.amount * this.free_coin_scale)}`)
              this.isLimit = true
              return
            }
          } else {
          }
        } else {
        }
      })
    },
    close() {
      this.$emit('cancel')
    },
    submit() {
      this.isLimit = false
      if (this.ruleForm.discount_config.status == 1) {
        this.handleAmountLimitDiscount()
      }

      if (!this.isLimit) {
        this.handleAmountLimit(this.ruleForm.first_list)
      }

      if (!this.isLimit) {
        this.handleAmountLimit(this.ruleForm.repeat_list)
      }
      if (this.isLimit) {
        return
      }
      setTimeout(() => {
        this.isLimit = false
      }, 2000)
      this.$refs.ruleForm.validate((valid) => {
        console.log(12321)
        if (valid) {
          this.loading = true
          this.rechargeAdd()
        } else {
        }
      })
    },
    rechargeAdd() {
      const first_money = this.ruleForm.first_list.find((item) => item.amount <= 0)
      const repeat_money = this.ruleForm.repeat_list.find((item) => item.amount <= 0)
      if (first_money || repeat_money) {
        console.log(333)
        this.$message.warning('充值金额不能为0')
        this.loading = false
        return false
      }
      this.ruleForm.first_list = this.ruleForm.first_list.map((item, index) => {
        return {
          ...item,
          sort: index
        }
      })
      this.ruleForm.repeat_list = this.ruleForm.repeat_list.map((item, index) => {
        return {
          ...item,
          sort: index
        }
      })

      if (this.ruleForm.discount_config.discount_info.free_coin) {
        if (this.ruleForm.discount_config.discount_info.free_coin[1]) {
          if (this.ruleForm.discount_config.discount_info.free_coin[0] === '0' && this.ruleForm.discount_config.discount_info.free_coin[1] !== '.') {
            this.ruleForm.discount_config.discount_info.free_coin = this.ruleForm.discount_config.discount_info.free_coin.substring(1)
            console.log()
          } else {
            this.ruleForm.discount_config.discount_info.free_coin
          }
        }
      }
      const data = JSON.parse(JSON.stringify(this.ruleForm))
      if (data.discount_config.status == 2) {
        data.discount_config = { status: 2 }
      } else {
        data.discount_config.discount_info.discount = data.discountNum
      }
      console.log(data, 'data')
      rechargeAdd(data).then((res) => {
        if (res.status_code === 1) {
          this.$message.success(res.msg)
          this.$emit('ok')
          this.close()
        }
        this.loading = false
      })
    },
    edit() {
      merchantUpdate(this.ruleForm).then((res) => {
        if (res.status_code === 1) {
          this.$message.success(res.msg)
          this.$emit('ok')
          this.close()
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.left {
  width: 400px;
  height: 100%;
  background-color: #fff;
  position: fixed;
  right: 800px;
  top: 0;
  .top {
    padding: 0 20px;
    height: 58px;
    display: flex;
    align-items: center;
    font-size: 16px;
    justify-content: space-between;
    i {
      font-size: 20px;
    }
  }
  .content {
    height: calc(100% - 58px);
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.messages {
  margin: 20px 20px 0 20px;
  display: flex;
  color: #e6a23c;
  background: #fdf6ec;
  border-radius: 4px;
  border: 1px solid #f2bc69;
  padding: 5px;
  .text {
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 20px;
    margin-left: 9px;
  }
}
.vip_amount {
  position: relative;
  .vip_year_tipe {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: -15px;
    font-size: 10px;
    color: red;
    height: 15px;
    line-height: 15px;
  }
}
.recommend {
  align-items: center;
  height: 40px;
}
.content {
  .form {
    padding: 20px;
  }
  .dialog-footer {
    position: relative;
  }
  .contentForm {
    width: 100%;
    height: calc(100% - 70px);
    overflow-y: auto;
  }
  .setLabel {
    span {
      font-size: 15px;
      font-weight: 500;
    }
  }
  .iconFont {
    font-size: 20px;
    color: #06c261;
    margin-left: 10px;
    position: relative;
    bottom: -2px;
    cursor: pointer;
  }
  .infoIcon {
    height: 40px;
    margin-left: 20px;
  }
  // 充值挽留
  .chargeRetain {
    margin-top: 20px;
    margin-bottom: 20px;
    .title {
      font-size: 15px;
      margin-bottom: 20px;
      font-weight: 500;
      color: #1d2129;
    }
    .chargeRetainContent {
      width: 100%;
      height: auto;
      background: #f7f8fa;
      padding: 20px;
      padding-bottom: 0;
      .attribute {
        width: 100%;
        height: 100px;
      }
      .huoLeft {
        position: relative;
        width: 1px;
        width: 15px;
        border-right: 2px solid rgba($color: #00bf8a, $alpha: 0.2);
        margin-right: 20px;
        height: 100%;
        .and_or {
          position: absolute;
          top: 50%;
          left: 5px;
          transform: translateY(-10px);
          color: #06c261;
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 18px;
          background: #eaf7f3;
          border-radius: 4px;
          cursor: pointer;
          user-select: none;
        }
      }
      .huoLeft::before {
        content: ' ';
        display: block;
        width: 15px;
        height: 1px;
        background: rgba($color: #00bf8a, $alpha: 0.5);
        position: absolute;
        left: 7px;
      }
      .huoLeft::after {
        content: ' ';
        display: block;
        width: 15px;
        height: 1px;
        background: rgba($color: #00bf8a, $alpha: 0.5);
        position: absolute;
        left: 7px;
        bottom: 0;
      }
      .huoRight {
        width: 100%;
        padding: 10px 0;
        .huoRightItem {
          margin-bottom: 20px;
        }
      }
    }
    .retainContent {
      width: 100%;
      height: auto;
      margin-top: 20px;
      padding-bottom: 20px;
      .subText {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #f6a400;
      }
      .rechargeContent {
        background: #fff;
        padding-left: 20px;
        margin-top: 10px;
      }
    }
    .gearRetain {
      margin-top: 15px;
      width: 100%;
      ::v-deep .el-form-item--small.el-form-item {
        margin-bottom: 0px;
      }
    }
  }
  .firstRecharge {
    width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 10px 0;
    .rechargeItem {
      background: #f7f8fa;
      margin-bottom: 5px;
      padding: 10px 0 0 10px;
      span {
        margin: 0 10px;
      }
      .subText {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #f6a400;
      }
    }
  }
}
</style>
